using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using com.paypal.sdk.profiles;
using com.paypal.sdk.services;
using com.paypal.sdk.util;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Common;

namespace Sedna.Payment.PayPal
{
    public class ECConfirmPaymentAction : PayPalAction
    {
        private string paymentDetailsUnbindPath;

        public override IActionResult Execute(IExecutionContext executionContext)
        {
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            profile.APIUsername = Api_Username;
            profile.APIPassword = Api_Password;
            profile.APISignature = Api_Signature;
            profile.Subject = string.Empty;
            profile.Environment = Environment;

            NVPCallerServices caller = new NVPCallerServices();
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder["METHOD"] = "DoExpressCheckoutPayment";
            encoder["TOKEN"] = HttpContext.Current.Request.QueryString["token"];
            encoder["PAYERID"] = HttpContext.Current.Request.QueryString["PayerID"];
            encoder["AMT"] = HttpContext.Current.Request.QueryString["amount"];
            encoder["PAYMENTACTION"] = HttpContext.Current.Request.QueryString["paymentType"];

            string requestForNvp = encoder.Encode();
            string nvpResponse = caller.Call(requestForNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(nvpResponse);

            string strAck = decoder["ACK"];
            if (strAck != null && (strAck == "Success" || strAck == "SuccessWithWarning"))
            {
                PaymentDetailsWrapper wrapper = new PaymentDetailsWrapper();
                wrapper.Token = decoder["TOKEN"];
                wrapper.TransactionID = decoder["TRANSACTIONID"];
                wrapper.OrderTime = decoder["ORDERTIME"];
                wrapper.TotalAmount = decoder["AMT"];
                wrapper.PaymentStatus = decoder["PAYMENTSTATUS"];

                executionContext.SetPropertyValue(paymentDetailsUnbindPath, wrapper);

                return CreateResult(successStatus);
            }
            else
            {
                return CreateErrorResult(executionContext, nvpResponse);
            }
        }
    }
}
